package com.fenxiangtech.mall.service.impl;

import com.fenxiangtech.mall.exception.ParameterMismatchException;
import com.fenxiangtech.mall.exception.ThemeMissException;
import com.fenxiangtech.mall.dao.ThemeDao;
import com.fenxiangtech.mall.entity.Image;
import com.fenxiangtech.mall.entity.Product;
import com.fenxiangtech.mall.entity.Theme;
import com.fenxiangtech.mall.service.ImageService;
import com.fenxiangtech.mall.service.ProductService;
import com.fenxiangtech.mall.service.ThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangjiashun
 */
@Service
public class ThemeServiceImpl implements ThemeService {

    @Autowired
    private ThemeDao themeDao;

    @Autowired
    private ImageService imageService;

    @Autowired
    private ProductService productService;

    @Override
    public Theme getSimpleThemeByID(Long themeID) {
        Theme theme = themeDao.getThemeByID(themeID);
        if (theme == null) {
            throw new ThemeMissException();
        }
        Image topicImage = theme.getTopicImage();
        Image headImage = theme.getHeadImage();
        if (topicImage != null) {
            topicImage = imageService.getImageById(topicImage.getId());
        }
        if (headImage != null) {
            headImage = imageService.getImageById(headImage.getId());
        }
        theme.setTopicImage(topicImage);
        theme.setHeadImage(headImage);
        return theme;
    }

    @Override
    public List<Theme> listSimpleThemeByIDs(String ids) {
        String[] idArr = ids.split(",");
        List<Theme> list = new ArrayList<>();
        for (int i = 0; i < idArr.length; i++) {
            Long id;
            try {
                id = Long.parseLong(idArr[i]);
            } catch (NumberFormatException e) {
                throw new ParameterMismatchException();
            }
            Theme theme = this.getSimpleThemeByID(id);
            list.add(theme);
        }
        return list;
    }

    @Override
    public Theme getThemeWithProducts(Long themeID) {
        Theme theme = getSimpleThemeByID(themeID);
        List<Product> products = productService.listSimpleProductByThemeID(themeID);
        theme.setProducts(products);
        return theme;
    }
}
